// 楼栋组
var buildingArr;
// 视频组
var videoArr;
//是否第一次加载
var isPostBack = true;

// 新老园区楼层视频
var cc1Build = [];
var oldBuild = [];
var cc1Video = [];
var oldVideo = [];

// 视频树加载状态
var hasLoadedTree = 0;

$(function () {
    queryListRole(1);
    initVideoTree();
    initBuildingTree();
});

// 获取列表信息
function queryListRole(pageIndex) {
    var videoGroupName = $('#groupNameSearchInp').val();
    var videoArea = $('#videoAreaSearchInp').val();

    $.getJSON('/cwp/src/json/system/video/videoGroup_v003.json',function(data){
        var loaderRoleTab = new LoaderTable("loaderRoleTab", "roleTab", "/cwp/front/sh/videoGroup!execute", "uid=v003&videoArea=" + videoArea + "&videoGroupName=" + videoGroupName, pageIndex, 10, roleResultArrived);
        // loaderRoleTab.Display();
        loaderRoleTab.loadSuccessed(data);
    });
}

// 生成表格
function roleResultArrived(result) {
    var thead = "<thead>" +
        "<tr>" +
        "<th>序号</th>" +
        "<th>园区</th>" +
        "<th>名称</th>" +
        "<th>操作</th>" +
        "</tr>" +
        "</thead>";
    var tbobys = "";
    tbobys = "<tbody>";
    for (var i = 0; i < result.beans.length; i++) {
        var groups = result.beans[i];
        var dellData = "'" + groups.id + "','" + groups.videoGroupName + "'";
        tbobys += "<tr><td>" + parseInt(i + 1) + "</td>" +
            "<td>" + (groups.videoArea == 1 ? "老园区" : "新园区") + "</td>" +
            "<td>" + groups.videoGroupName + "</td>" +
            "<td>" +
            "<a class='t-btn t-btn-sm t-btn-blue' onclick=editGroup('" + groups.id + "')>修改</a>" +
            "<a class='t-btn t-btn-sm t-btn-red' onclick=dellGroup(" + dellData + ")>删除</a>" +
            "</td>" +
            "</tr>"
    }
    tbobys += "</tbody>";
    //显示表格html
    $('#roleTab').html(thead + tbobys);
}

// 回调函数当前页
function paginationCallback(page_index) {
    if (!isPostBack) {
        queryListRole(page_index + 1);
    }
}

//搜索视频列表
$("#groupNameSearchBtn").on("click", function () {
    isPostBack = true;
    queryListRole(1);
});

// 获取视频下拉树
function initVideoTree() {
    // PostForm("/cwp/front/sh/device!execute", "uid=d001&deviceTypeId=1010&currentPage=1&pageSize=5000", "", function (result) {
    //     if (result.returnCode == 0) {
    //         videoArr = result.beans;
    //         if (buildingArr && buildingArr.length) {
    //             getDeptTree();
    //         }
    //     }
    // }, "", "frm");
    $.getJSON('/cwp/src/json/system/video/device_d001.json',function(result){
        if (result.returnCode == 0) {
            videoArr = result.beans;
            if (buildingArr && buildingArr.length) {
                getDeptTree();
            }
        }
    });
}

//获取楼层树数据
function initBuildingTree() {
    // PostForm("/cwp/front/sh/intebuilding!execute", "uid=building004", "", function (result) {
    //     if (result.returnCode == 0) {
    //         buildingArr = result.beans;
    //         if (videoArr && videoArr.length) {
    //             getDeptTree();
    //         }
    //     }
    // }, "", "frm");
    $.getJSON('/cwp/src/json/system/video/intebuilding_building004.json',function(result){
        if (result.returnCode == 0) {
            buildingArr = result.beans;
            if (videoArr && videoArr.length) {
                getDeptTree();
            }
        }
    });
}

//获取数据初始化视频树
function getDeptTree() {
    // 保存楼层信息
    var cc1Id;
    var oldId;

    var buildingArrFull = [];

    var cc1Area = [];

    var videoFull = [];

    //数据排序
    buildingArr.forEach(function (v, i) {
        var obj = {};
        obj.id = v.buildingId;
        obj.pId = v.parentId;
        obj.name = v.buildingDesc;
        obj.type = v.buildingType;
        if (i == 0) {
            obj.open = true;
        }
        buildingArrFull.push(obj);
    });

    // 区分新老园区楼层
    buildingArrFull.forEach(function (v) {
        if (v.type == "1") {
            if (v.name == "cc-1") {
                cc1Id = v.id;
            }
            // else if(v.name == "老园区生产楼"){
            // 	oldId = v.id;
            // }
        }
    });
    buildingArrFull.forEach(function (v) {
        if (v.type == "3") {
            if (v.pId == cc1Id) {
                cc1Build.push(v);
            }
            // else if(v.pId == oldId){
            // 	oldBuild.push(v);
            // }
        }
    });
    cc1Build.forEach(function (value) {
        buildingArrFull.forEach(function (v) {
            if (v.type == "2") {
                if (v.pId == value.id) {
                    cc1Area.push(v);
                }
            }
        });
    });
    // 合并cc-1楼栋区域数组
    cc1Build.push.apply(cc1Build, cc1Area);

    // 区分新老园区视频
    videoArr.forEach(function (v) {
        var obj = {};
        obj.id = v.deviceId;
        obj.pId = v.buildingId;
        obj.name = v.devicePositionDescribe;
        obj.type = '1010';
        videoFull.push(obj);
    });
    var isExist = 0;
    videoFull.forEach(function (value) {
        isExist = 0;
        cc1Build.forEach(function (v) {
            if (value.pId == v.id) {
                cc1Video.push(value);
                isExist = 1;
            }
        });
        if (!isExist) {
            oldVideo.push(value);
        }
    });
    var cc1VideoSimpOnly = cc1Video.concat();
    // 合并数组
    // 老园区
    // oldBuild.push.apply(oldBuild, oldVideo);
    oldVideo.push.apply(oldVideo, oldBuild);
    // 新园区
    // cc1Build.push.apply(cc1Build, cc1Video);
    cc1Video.push.apply(cc1Video, cc1Build);

    // 屏蔽无关楼层
    var cc1VideoSimp = [];
    cc1Video.forEach(function (value) {
        if (value.type == "2") {
            var isExistVideo = 0;
            for(var i = 0 ; i < cc1VideoSimpOnly.length ; i++){
                if (value.id == cc1VideoSimpOnly[i].pId) {
                    isExistVideo = 1;
                    break;
                }
            }
            if(isExistVideo){
                cc1VideoSimp.push(value)
            }
        } else if (value.type == "3") {
            var isExistVideo = 0;
            for(var i = 0 ; i < cc1Video.length ; i++){
                if(cc1Video[i].type == "2" && value.id == cc1Video[i].pId){
                    isExistVideo = 1;
                    break;
                }
            }
            for(var i = 0 ; i < cc1VideoSimpOnly.length ; i++){
                if(value.id == cc1VideoSimpOnly[i].pId){
                    isExistVideo = 1;
                    break;
                }
            }
            if(isExistVideo){
                cc1VideoSimp.push(value)
            }
        } else if (value.type == "1010") {
            cc1VideoSimp.push(value)
        }
    });
    // //配置组织结构树
    var setting = {
        check: {
            enable: true,
            chkboxType: {"Y": "ps", "N": "ps"}
        },
        data: {
            simpleData: {
                enable: true
            }
        },
        view: {
            showIcon: false
        }
    };

    $.fn.zTree.init($("#treeOrg1"), setting, oldVideo);

    $.fn.zTree.init($("#treeOrg2"), setting, cc1VideoSimp);

    $('#treeOrg1').slimScroll({
        width: '320px', //可滚动区域宽度
        height: '305px', //可滚动区域高度
        size: '5px' //组件宽度
    });
    $('#treeOrg2').slimScroll({
        width: '320px', //可滚动区域宽度
        height: '305px', //可滚动区域高度
        size: '5px' //组件宽度
    });
    hasLoadedTree = 1;
}

//新增视频组
$("#btnAddGroup").on("click", function () {
    $("#modalGroup .modal-title").text("新增视频组");
    addGroupValidator();
    //情况表单和验证
    $("input:radio[name='videoArea']").removeAttr('disabled');
    $("input:radio[name='videoArea'][value='2']").prop("checked", "checked");

    $("#groupNameTip").html("").attr("class", "");
    $("#videoGroupName").val("");
    $("#videoGroupNameBefore").val("");
    $("#manageGrupId").val('');
    $("#manageGrupListBefore").val("");

    emptyVideoGroup();
    seleVideoGroup();

    $("#modalGroup").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
});

// 修改视频组
function editGroup(groupId) {
    if (hasLoadedTree) {
        $("#modalGroup .modal-title").text("修改视频组");
        //编辑视频组验证
        addGroupValidator();

        // PostForm("/cwp/front/sh/videoGroup!execute", "uid=v009&id=" + groupId, "", function (result) {
        //     var rsData = result.bean;
        //     if (result.returnCode == 0) {
        //         $("input:radio[name='videoArea']").attr('disabled', 'disabled');
        //         $("input:radio[name='videoArea'][value=" + rsData.videoArea + "]").prop("checked", "checked");
        //
        //         $("#groupNameTip").html("").attr("class", "");
        //         $('#videoGroupNameBefore').val(rsData.videoGroupName);
        //         $('#videoGroupName').val(rsData.videoGroupName);
        //         if (result.object) {
        //             $('#manageGrupListBefore').val(result.object.toString());
        //         } else {
        //             $('#manageGrupListBefore').val('');
        //         }
        //         $('#manageGrupId').val(groupId);
        //
        //         emptyVideoGroup();
        //         seleVideoGroup();
        //
        //         updateMenuResultArrived(result.object, rsData.videoArea);
        //
        //         $("#modalGroup").modal({
        //             keyboard: true,
        //             backdrop: 'static'
        //         }).on('show.bs.modal', centerModal());
        //     } else {
        //         tipModal("icon-cross", result.returnMessage);
        //     }
        // }, "", "frm");

        $.getJSON('/cwp/src/json/system/video/videoGroup_v009.json',function(result){
            var rsData = result.bean;
            if (result.returnCode == 0) {
                $("input:radio[name='videoArea']").attr('disabled', 'disabled');
                $("input:radio[name='videoArea'][value=" + rsData.videoArea + "]").prop("checked", "checked");

                $("#groupNameTip").html("").attr("class", "");
                $('#videoGroupNameBefore').val(rsData.videoGroupName);
                $('#videoGroupName').val(rsData.videoGroupName);
                if (result.object) {
                    $('#manageGrupListBefore').val(result.object.toString());
                } else {
                    $('#manageGrupListBefore').val('');
                }
                $('#manageGrupId').val(groupId);

                emptyVideoGroup();
                seleVideoGroup();

                updateMenuResultArrived(result.object, rsData.videoArea);

                $("#modalGroup").modal({
                    keyboard: true,
                    backdrop: 'static'
                }).on('show.bs.modal', centerModal());
            } else {
                tipModal("icon-cross", result.returnMessage);
            }
        });
    } else {
        tipModal("icon-info", '加载中...');
    }
}

//新增修改验证
function addGroupValidator() {
    $.formValidator.initConfig({
        formid: "frmMain", onerror: function () {
            return false;
        }, onsuccess: function () {
            return true;
        }
    });

    $("#videoGroupName").formValidator({
        onfocus: "请输入视频组名称",
        oncorrect: " "
    }).InputValidator({
        min: 2,
        max: 20,
        onempty: "请输入视频组名称",
        onerror: "视频组名称长度为2到10个字符"
    }).RegexValidator({
        regexp: "illegal",
        datatype: "enum",
        onerror: "视频组名称不能含有特殊字符"
    });
}

//填充树状结构图
var updateMenuResultArrived = function (Groups, Area) {
    var treeObj = $.fn.zTree.getZTreeObj("treeOrg" + Area);
    var chd = "";
    if (Groups) {
        for (var i = 0; i < Groups.length; i++) {
            chd = treeObj.getNodeByParam("id", Groups[i], null);
            //判断是否存在子节点
            if (chd) {
                if ("children" in chd) {
                    chd.open = true;
                } else {
                    //遍历选择树状权权限
                    treeObj.checkNode(treeObj.getNodeByParam("id", Groups[i], null), true, true);
                }
            }
        }
    }
};

// 视频组保存
$("#saveGroupBtn").on("click", function () {
    //判断表单验证是否通过
    if ($.formValidator.PageIsValid()) {
        var Group = $('#manageGrupId').val();
        var groupName;
        var option;
        if (Group == '') {
            //新增
            groupName = $("#videoGroupName").val();

            option = {
                uid: 'v001',
                createId: localStorage.getItem("parkId"),
                idStr: zTreeOnClick().toString(),
                videoGroupName: groupName,
                videoArea: document.getElementById("videoAreaOldRadio").checked ? "1" : "2"
            };
        }
        else {
            //修改
            var idStr = zTreeOnClick().toString();
            // var idStr = $("#manageGrupListBefore").val() == groups ? "" : groups;

            if ($("#manageGrupListBefore").val() == idStr && $("#videoGroupName").val() == $("#videoGroupNameBefore").val()) {
                //关闭模态框
                return $("#modalGroup").modal("hide");
            }

            option = {
                uid: 'v002',
                createId: localStorage.getItem("parkId"),
                idStr: idStr,
                id: Group,
                videoGroupName: $("#videoGroupName").val() == $("#videoGroupNameBefore").val() ? "" : $("#videoGroupName").val()
            }
        }


        // $.ajax({
        //     timeout : 30000,
        //     type: 'POST',
        //     url: '/cwp/front/sh/videoGroup!execute',
        //     beforeSend:function(requests){
        //         requests.setRequestHeader("platform", "pc");
        //     },
        //     async:true,
        //     dataType: "json",
        //     data: option,
        //     success:function (result) {
        //         if (+result.returnCode) {
        //             return tipModal('icon-cross', result.returnMessage);
        //         }
        //
        //         isPostBack = true;
        //         queryListRole(1);
        //
        //         //关闭模态框
        //         $("#modalGroup").modal("hide");
        //         tipModal("icon-checkmark", result.returnMessage);
        //     },
        //     error:function (result) {
        //         //超时提示
        //         if(result.statusText=='timeout'){
        //             return tipModal('icon-cross', "服务器通信超时，请稍后再试");
        //         }
        //
        //     }
        // });

        $.getJSON('/cwp/src/json/system/video/videoGroup_add_update.json',function(result){
            if (+result.returnCode) {
                return tipModal('icon-cross', result.returnMessage);
            }

            isPostBack = true;
            queryListRole(1);

            //关闭模态框
            $("#modalGroup").modal("hide");
            tipModal("icon-checkmark", result.returnMessage);
        });
    }
});

// 切换新老园区视频组
$('#seleVideoAreaRadioLi').on("click", function () {
    seleVideoGroup();
});
var seleVideoGroup = function () {
    $(".treeOrgDiv").addClass('hide');
    if (document.getElementById("videoAreaOldRadio").checked) {
        $("#treeOrgDiv1").removeClass('hide');
    } else {
        $("#treeOrgDiv2").removeClass('hide');
    }
};

// 清空视频组选中
var emptyVideoGroup = function () {
    var treeObj1 = $.fn.zTree.getZTreeObj("treeOrg1");
    if (treeObj1) {
        treeObj1.checkAllNodes(false);
    }
    var treeObj2 = $.fn.zTree.getZTreeObj("treeOrg2");
    if (treeObj2) {
        treeObj2.checkAllNodes(false);
    }
};

// 删除视频组
var dellGroup = function (Group, name) {
    $('#dellGroupName').text(name);
    $('#dellModelId').val(Group);
    $("#dellModel").modal({
        keyboard: true,
        backdrop: 'static'
    }).on('show.bs.modal', centerModal());
};

// 删除确认
$("#saveDellBtn").on("click", function () {
    // PostForm("/cwp/front/sh/videoGroup!execute", "uid=v005&id=" + $('#dellModelId').val(), "", function (result) {
    //     if (result.returnCode == 0) {
    //         tipModal("icon-checkmark", result.returnMessage);
    //         isPostBack = true;
    //         queryListRole(1);
    //     } else {
    //         tipModal("icon-cross", result.returnMessage);
    //     }
    // }, "", "frm");

    $.getJSON('/cwp/src/json/system/video/videoGroup_v005.json',function(result){
        if (result.returnCode == 0) {
            tipModal("icon-checkmark", result.returnMessage);
            isPostBack = true;
            queryListRole(1);
        } else {
            tipModal("icon-cross", result.returnMessage);
        }
    });
    $("#dellModel").modal("hide");
});

//视频组选择
function zTreeOnClick() {
    var groupArr = [];
    var treeObj;
    var buildArr = [];
    if (document.getElementById("videoAreaOldRadio").checked) {
        treeObj = $.fn.zTree.getZTreeObj("treeOrg1");
        buildArr = oldBuild;
    } else {
        treeObj = $.fn.zTree.getZTreeObj("treeOrg2");
        buildArr = cc1Build;
    }
    var nodes = treeObj.getCheckedNodes(true);
    // 去除楼层
    var exist = 0;
    for (var i = 0; i < nodes.length; i++) {
        exist = 0;
        for (var j = 0; j < buildArr.length; j++) {
            if (nodes[i].id == buildArr[j].id) {
                exist = 1;
                break;
            }
        }
        if (!exist) {
            groupArr.push(nodes[i].id);
            exist = 0;
        }
    }
    return groupArr;
}